package com.itheima.tlias08_14.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias08_14.VO.PageVO;
import com.itheima.tlias08_14.dto.StatisticEmpGenderDTO;
import com.itheima.tlias08_14.entity.Clazz;
import com.itheima.tlias08_14.entity.Emp;
import com.itheima.tlias08_14.mapper.ClazzMapper;
import com.itheima.tlias08_14.mapper.EmpMapper;
import com.itheima.tlias08_14.mapper.ExprMapper;
import com.itheima.tlias08_14.paramobject.ExprPO;
import com.itheima.tlias08_14.paramobject.InsertEmp;
import com.itheima.tlias08_14.dto.SelectEmp;
import com.itheima.tlias08_14.dto.SelectEmpById;
import com.itheima.tlias08_14.paramobject.SelectPageParam;
import com.itheima.tlias08_14.service.EmpService;
import com.itheima.tlias08_14.utils.ResultUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Slf4j
@Service
public class EmpServiceImp implements EmpService {

    @Resource
    EmpMapper mapper;


    @Autowired
    ExprMapper exprMapper;



    @Override
    public ResultUtil selectEmp(SelectPageParam selectPageParam) {
        //分页查询
        Page<Object> page = PageHelper.startPage(selectPageParam.getPage(), selectPageParam.getPageSize());
            List<SelectEmp> emps = mapper.selectEmp(selectPageParam);
        PageVO<SelectEmp> pageVO = new PageVO<>();
         pageVO.setTotal(page.getTotal());
         pageVO.setRows(emps);
         return ResultUtil.success(pageVO);
    }


    @Resource
    ClazzMapper clazzMapper;
    //启动事务  识别是否出现异常，如果出现异常，回滚事务
    //事务在私有方法中 回滚会失效
    //事务在tray catch 中 回滚失效
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteEmpById(List<Integer> ids) {
        //删除员工之前先判断员工是否为某班级的班主任
        List<StatisticEmpGenderDTO> clazzMasterIds = clazzMapper.selectByMasterId(ids);
        if(clazzMasterIds != null && !clazzMasterIds.isEmpty()){
            //若为班主任的将对应班级的班主任id替换为0
            clazzMasterIds.forEach(masterIds -> {
                Clazz clazz = new Clazz();
                clazz.setId(masterIds.getValue());
                int i = clazzMapper.updateClazz(clazz);
            });
        }
        int i = mapper.deleteEmpById(ids);
        //删完员工信息后 删除对应的expr
        int j = exprMapper.batchDeleteExprByEmpId(ids);
        log.info("expr删除{}",j);
        return i;
    }

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    @Override
    public int insertEmp(InsertEmp insertEmp) {
        //判断插入的信息用户名是否已经存在
        for (Emp e : mapper.selectAllEmp()) {
            if(e.getUsername().equals(insertEmp.getUsername())){
                return 0;
            }
        }
        //主键回显 id
        StringUtils.isEmpty(insertEmp.getEntryDate());
        if(insertEmp.getEntryDate() == null || insertEmp.getEntryDate().isBlank())
        {
            insertEmp.setEntryDate(LocalDate.now().toString());
        }
        int flag = mapper.insertEmp(insertEmp);
        if(insertEmp.getExprList() != null && !insertEmp.getExprList().isEmpty()){
            List<ExprPO> exprList = insertEmp.getExprList();
            for (ExprPO exprPO : exprList) {
                exprPO.setEmpId(insertEmp.getId());
            }
            int i = exprMapper.batchInsertExpr(exprList);
            log.info("expr插入{}",i);
        }
        return flag;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SelectEmpById selectEmpById(Integer id) {
        SelectEmpById empById = mapper.selectEmpById(id);
        List<ExprPO> exprPOs = exprMapper.selectExprByEmpId(id);
        empById.setExprList(exprPOs);
        return empById;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateEmp(SelectEmpById emp) {
        //判断更新的信息用户名是否已经存在
        for (Emp e : mapper.selectAllEmp()) {
            if(e.getId() != emp.getId() && e.getUsername().equals(emp.getUsername())){
                return 0;
            }
        }

        int t = exprMapper.batchDeleteExprByEmpId(List.of(emp.getId()));
        log.info("把原有expr数据先删除{}",t);
        if(emp.getExprList() != null && !emp.getExprList().isEmpty()){
            List<ExprPO> exprList = emp.getExprList();
            for (ExprPO exprPO : exprList) {
                exprPO.setEmpId(emp.getId());
            }
            int j = exprMapper.batchInsertExpr(emp.getExprList());
            log.info("新expr数据插入{}",j);
        }
        return mapper.updateEmp(emp);
    }

    @Override
    public List<Emp> selectAllEmp() {
        List<Emp> employees = mapper.selectAllEmp();
        return employees;
    }
}
